package zmee.pur.src.common;

import com.alibaba.druid.util.StringUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.IFormView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.constant.BillAssistConstant;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.constant.SrcCommonConstant;
import kd.scm.pds.common.constant.SrcMetadataConstant;
import kd.scm.pds.common.enums.BidDocTypeEnums;
import kd.scm.pds.common.extplugin.ExtPluginContext;
import kd.scm.pds.common.extplugin.ExtPluginFactory;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.pds.common.util.PdsOrderByUtils;
import kd.scm.pds.common.util.TemplateUtil;
import kd.scm.src.common.bidopen.SrcBidOpenFacade;
import kd.scm.src.common.util.SrcComponentUtil;
import kd.scm.src.formplugin.compext.SrcQuoteBillAttachHandler;
import kd.scm.src.formplugin.compext.SrcSupplierEnrollAttachHandler;

import java.util.EventObject;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/02/17/14:45
 * @Description: 评标时查看供应商标书文件(按是否开标以及开标标段过滤)
 */
public class SrcBidAssessDocEditExt extends AbstractBillPlugIn {
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IFormView view = this.getView();
        DynamicObject billObj = null;
        String entityName = null;
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        long projectId = PdsCommonUtils.object2Long(paramMap.get(SrcCommonConstant.PROJECT));
        if (projectId == 0) {
            IFormView parentView = view.getParentView();
            // 父单据页面
            if (parentView == null) {
                return;
            }
            billObj = parentView.getModel().getDataEntity(true);
            projectId = SrmCommonUtil.getPkValue(billObj);
        } else {
            String baseType = PdsCommonUtils.object2String(paramMap.get(SrcCommonConstant.BASETYPE), "");
            if (baseType.equals(paramMap.get(SrcCommonConstant.BASETYPE_APTITUDE))) {
                entityName = SrcMetadataConstant.SRC_APTITUDEAUDIT;
            } else if (baseType.equals(paramMap.get(SrcCommonConstant.BASETYPE_APTITUDE2))) {
                entityName = SrcMetadataConstant.SRC_APTITUDEAUDIT2;
            } else {
                entityName = SrcMetadataConstant.SRC_SCORERTASK;
            }
            billObj = BusinessDataServiceHelper.loadSingle(projectId, entityName);
        }
        this.getModel().setValue(SrcCommonConstant.PROJECTF7, projectId);

        // 过滤条件：项目Id
        QFilter bidDocFilter = new QFilter(SrcCommonConstant.PROJECT + "." + SrcCommonConstant.ID, QCP.equals, projectId);

        // 业务状态 为已开标
        QFilter statusFilter = new QFilter(BillAssistConstant.ENTRY_STATUS, QCP.equals, "C");
        // 或状态为待投标，且供应商为0
        statusFilter.or(new QFilter(BillAssistConstant.ENTRY_STATUS, QCP.equals, "A").and(SrcCommonConstant.SUPPLIER, QCP.equals, 0));
        // 条件合并
        bidDocFilter.and(statusFilter);

        // 资质审查(资质后审不控制）
        if (SrcMetadataConstant.SRC_APTITUDEAUDIT.equals(entityName)) {
            // 标书类型=资质审查
            bidDocFilter.and(SrcCommonConstant.PACKFILETYPE, QCP.equals, BidDocTypeEnums.APT_DOC.getValue());
        } else {
            // 如果是 评标任务（评委），还需要再按 标段过滤
            if (StringUtils.equals(entityName, SrcMetadataConstant.SRC_SCORERTASK)) {
                // 如果标段管理方式=2 -按标段，还需要增加标段过来
                if (SrcCommonConstant.MANAGETYPE_BYPACKAGE.equals(SrcComponentUtil.getManagetype(this.getView()))) {
                    bidDocFilter = bidDocFilter.and(SrcCommonConstant.PACKAGE + "." + SrcCommonConstant.ID, QCP.in, getPackageSet());
                }
            }
        }
        // 不需要赋值的字段
        Set<String> excFields = new HashSet<String>();
        excFields.add(BillAssistConstant.ID);
        excFields.add(BillAssistConstant.SEQ);

        // 装载数据
        String orderBy = PdsOrderByUtils.getOrderByString("orderby003");
        TemplateUtil.loadCompEntryData(this.getView(), SrcMetadataConstant.SRC_BIDDOCTPLF7, bidDocFilter, excFields,
                SrcCommonConstant.ENTRYENTITY, orderBy, false);

        // 装载供应商报名的附件
        loadEnrollAttach(projectId, excFields);

        // 加载 报价单的单据附件
        loadQuoteBillAttach();

        // 隐藏供应商名称
        SrcBidOpenFacade.hideSupplierName(this.getView(), projectId);
    }

    private Set<Long> getPackageSet() {
        QFilter qFilter = (new QFilter("scorer", "=", RequestContext.get().getCurrUserId())).or("billid.creator", "=",
                RequestContext.get().getCurrUserId());
        DynamicObjectCollection rows = QueryServiceHelper.query("src_scoretask_scorerf7", "package.id", new QFilter[]{qFilter});
        return (Set) rows.stream().map((row) -> {
            return row.getLong("package.id");
        }).collect(Collectors.toSet());
    }

    private void loadEnrollAttach(long projectId, Set<String> excludedFields) {
        ExtPluginContext context = new ExtPluginContext();
        context.setView(this.getView());
        context.setProjectId(projectId);
        context.setExcludedFields(excludedFields);
        ExtPluginFactory.executeExtplugin(SrcSupplierEnrollAttachHandler.class.getSimpleName(), context, true);
    }

    private void loadQuoteBillAttach() {
        ExtPluginContext context = new ExtPluginContext();
        context.setView(this.getView());
        ExtPluginFactory.executeExtplugin(SrcQuoteBillAttachHandler.class.getSimpleName(), context, true);
    }
}
